<?php

/**
 * This is the model class for table "category".
 *
 * The followings are the available columns in table 'category':
 * @property string $id
 * @property string $parent_id
 * @property string $name
 * @property integer $status
 * @property string $description
 * @property integer $created_time
 * @property integer $created_by
 * @property integer $modified_time
 * @property integer $modified_by
 */
class Category extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Category the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'category';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('name, status, created_time, created_by', 'required'),
			array('status, created_time, created_by, modified_time, modified_by', 'numerical', 'integerOnly'=>true),
			array('parent_id', 'length', 'max'=>4),
			array('name', 'length', 'max'=>255),
			array('description', 'safe'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, parent_id, name, status, description, created_time, created_by, modified_time, modified_by', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		return array(
			'Product' => array(self::HAS_MANY, 'Product', 'category_id'),
			'parent' => array(self::BELONGS_TO, 'Category', 'parent_id'),
			'childs' => array(self::HAS_MANY, 'Category', 'parent_id'),
		);
	}
        public function scopes() {
        return array(            
            'rootcate' => array(
                'condition' => 'parent_id= 0',)
        );
    }
	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'parent_id' => 'Parent',
			'name' => 'Name',
			'status' => 'Status',
			'description' => 'Description',
			'created_time' => 'Created Time',
			'created_by' => 'Created By',
			'modified_time' => 'Modified Time',
			'modified_by' => 'Modified By',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search(array $time = NULL)
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;
		$criteria->compare('id',$this->id,true);
		$criteria->compare('parent_id',$this->parent_id,true);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('description',$this->description,true);
//		$criteria->compare('created_time','>'.$time['created_from']);
//        $criteria->compare('created_time','<'.$time['created_to']);
		$criteria->compare('created_by',$this->created_by);
//		$criteria->compare('modified_time','>'.$time['modified_from']);
//        $criteria->compare('modified_time','<'.$time['modified_to']);
		$criteria->compare('modified_by',$this->modified_by);

		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
    
    public function getParentName(){
        if ($this->parent_id == 0)
            return "Root";
        $model = Category::model()->findByPk($this->parent_id);
        if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
        return $model->getAttribute('name');
    }
    
    public function getStatusName(){
        if ($this->status == 0)
                return "disable";
        else
            return 'enable';
    }
    
    public static function findSonCategory($parent_id = 0){
        $categories = self::model()->findAllByAttributes(array('parent_id' => $parent_id));
        return $categories;
    }
    public static function findTreeCategory($id = 0){
        $categories = self::findSonCategory($id);
        if ($categories == null)
            return;
        $tree = array();
        foreach ($categories as $category)
            $tree[] = array(
                'text' => CHtml::link(CHtml::encode($category['name']), array('view', 'id'=>$category['id'])),
                'children' => self::findTreeCategory($category->attributes['id'])
            );
        return $tree;
    }
    
    public static function listCategory($id = 0){
        $categories = self::findSonCategory($id);
        if ($categories == null){
           // $cate = self::model()->findByPk($id);
           // return array($cate->id => '--'.$cate->name);
        }
        $trees = array();
        foreach ($categories as $category){
            $trees = $trees + array($category->id => $category->name) + self::listCategory($category->id);
            
        }
        
        foreach ($trees as $key => $value){
            $trees[$key] = '--'.$value;
        }
        
        return $trees;
    }
    
    public static function getChilds($id) {
		$data = array();
        $category = Category::model()->findAll('parent_id = ' . $id);
        if ($category != null){
            foreach($category as $model) {
                
                if ((isset ($_GET['id'])&&$model->id == $_GET['id']))
                    $row['text'] = CHtml::link($model->name, array('category/view', 'id' => $model->id,), array('style' => 'background:#f5f5f5;color:#333',));
                else 
                    $row['text'] = CHtml::link($model->name, array('category/view', 'id' => $model->id,), array());
                $row['id'] = $model->id;
                $row['children'] = Category::getChilds($model->id);
                $data[] = $row;
            }
        }
		return $data;
	}
    public static function getListed() {
		$subitems = array();
		if($this->childs) foreach($this->childs as $child) {
			$subitems[] = $child->getListed();
		}
		$returnarray = array('label' => $this->name, 'url' => array('Category/view', 'id' => $this->category_id));
		if($subitems != array()) $returnarray = array_merge($returnarray, array('items' => $subitems));
		return $returnarray;
	}
        public static function listCategoryProduct() {
        $cateProducts = self::model()->findAll('parent_id = 0');
        $arr = array();
        foreach ($cateProducts as $cateProduct) {
            
            $cateComs = self::model()->findAll('parent_id = '.$cateProduct->id);
            foreach ($cateComs as $cateCom) {
            $arr[$cateCom->id] = $cateProduct->name. ' > ' . $cateCom->name;
        }
        }
        
        return $arr;
    }
}